package com.captain.special.二叉树.中等;

import com.captain.leetcode.TreeNode;

/**
 * Des:
 *
 * @author XL
 * @Date 2022/5/21 23:07
 */
public class 最长同值路径687 {
    int max = 0;
    public int longestUnivaluePath(TreeNode root) {
        if(root == null) return 0;
        recur(root);
        return max;
    }

    public int recur(TreeNode node) {
        if(node.left == null && node.right == null) {
            return 0;
        }
        int leftSize = 0;
        int rightSize = 0;
        //求路径
        //左边路径
        if(node.left != null) {
            int left = recur(node.left) + 1;
            leftSize = node.val == node.left.val ? left : 0;
        }

        if(node.right != null) {
            int right = recur(node.right) + 1;
            rightSize = node.val == node.right.val ? right : 0;
        }
        max = Math.max(max,leftSize+rightSize);
        return Math.max(leftSize,rightSize);
    }
}
